package com.uujava.minibox.ui.button;
import java.awt.AlphaComposite;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

import com.mxcyk.serviceLogic.VerticalFlowLayout;


/**
 * @author k
 *  图片按钮，可设置按钮大小自动根据按钮大小，
 *  图片覆盖整个按钮，包括按钮名称。多种构造方法
 * 	已经实现一种监听某种事件的构造方法
 *  个非图片按钮用也可以，把图片路径赋值为 空，
 *  日期：2012-8-8
 *  修改:
 *  	日期:2013年7月27日18:33:25	添加了动画效果
 *  	日期:2013年7月30日12:13:54	更改原来的点击出发动画改为鼠标移入触发
 */
@SuppressWarnings("serial")
public class ImageJButton extends JButton implements ActionListener,MouseListener {
	private Image img;
	private int width;// 设置图片的宽
	private int height;// 设置图片的高
	private int left;// 距离上层容器左端的距离
	private int top;// 距离上层容器的上端的距离
	/***********************动画效果**************************************/
	float alpha = 1.0f; // current opacity of button
	Timer timer; // for later start/stop actions
	int animationDuration = 2000; // each animation will take 2 seconds
	long animationStartTime; // start time for each animation
	BufferedImage buttonImage = null;
	/********************************************************************/
	// 空参构造方法
	public ImageJButton() {
		/*********动画特效设置*******************/
		setOpaque(false);
		timer = new Timer(30, this);
		addMouseListener(this);
		/***************************************/
	}

	// 带图片路径的构造方法
	public ImageJButton(String imgPath) {
		img = new ImageIcon(imgPath).getImage();// 根据图片路径得到Icon，并得到image图片对象
		/*********动画特效设置*******************/
		setOpaque(false);
		timer = new Timer(30, this);
		addMouseListener(this);
		/***************************************/
	}

	// 带图片路径并且能设置图片大小的构造方法
	public ImageJButton(String imgPath, int width, int height) {
		/*********动画特效设置*******************/
		setOpaque(false);
		timer = new Timer(30, this);
		addMouseListener(this);
		/***************************************/
		
		ImageIcon im=null;
		try {
			//此段代表是为了应对达成jar包后读取资源文件
			im = new ImageIcon(getClass().getResource(imgPath));
			img = im.getImage();
		} catch (Exception e) {
			System.out.println("在ImageJButton类获取图片时出错");
			System.out.println("图片错误路径为"+imgPath);
		}finally{
			im=null;
		}
		
		
		//img = new ImageIcon(imgPath).getImage();
		this.width = width;
		this.height = height;
		this.setPreferredSize(new Dimension(width, height));
	}
	
	// 带图片并且能设置图片大小的构造方法
	public ImageJButton(ImageIcon imageIcon, int width, int height) {
		/*********动画特效设置*******************/
		setOpaque(false);
		timer = new Timer(30, this);
		addActionListener(this);
		/***************************************/
		
		img = imageIcon.getImage();
		this.width = width;
		this.height = height;
		this.setPreferredSize(new Dimension(width, height));
	}
	/*
	 * 带图片路径并且能设置图片大小和图片名字的构造方法构造方法中写入按钮名字，
	 * 以便读取按钮名字，但是名字不会显示出来，
	 * 会被绘图覆盖，能在事件监听时候通过读取按钮名称判断执行事件监听的是某个按钮
	 */
	public ImageJButton(String name, String imgPath, int width, int height) {
		super(name);
		img = new ImageIcon(imgPath).getImage();
		this.width = width;
		this.height = height;
		this.setPreferredSize(new Dimension(width, height));
		/*********动画特效设置*******************/
		setOpaque(false);
		timer = new Timer(30, this);
		addMouseListener(this);
		/***************************************/
	}
	/*
	 * 带图片并且能设置图片大小和图片名字的构造方法构造方法中写入按钮名字，
	 * 以便读取按钮名字，但是名字不会显示出来，
	 * 会被绘图覆盖，能在事件监听时候通过读取按钮名称判断执行事件监听的是某个按钮
	 */
	public ImageJButton(String name, ImageIcon icon, int width, int height) {
		super(name);
		img = icon.getImage();
		this.width = width;
		this.height = height;
		this.setPreferredSize(new Dimension(width, height));
		/*********动画特效设置*******************/
		setOpaque(false);
		timer = new Timer(30, this);
		addMouseListener(this);
		/***************************************/
	}

	// 下面这个方法看不懂你不用管他，知道有这个绘图的方法就好了，2D图片都可以这样覆盖
	@Override
	public void paintComponent(Graphics g) {// 覆盖paintComponent方法,绘图功能
		super.paintComponent(g);
		/*******************************动画绘图***************************************************/
		// Create an image for the button graphics if necessary
//
//		buttonImage = getGraphicsConfiguration().createCompatibleImage(
//				getWidth(), getHeight());
//
//		Graphics gButton = buttonImage.getGraphics();
//		gButton.setClip(g.getClip());
//
//		// Have the superclass render the button for us
//		super.paintComponent(gButton);

		// Make the graphics object sent to this paint() method translucent
		Graphics2D g2d = (Graphics2D) g;
		AlphaComposite newComposite = AlphaComposite.getInstance(
				AlphaComposite.SRC_OVER, alpha);
		g2d.setComposite(newComposite);

		// Copy the button's image to the destination graphics, translucently
		//g2d.drawImage(buttonImage, 0, 0, null);
		/**********************************************************************************/
		Graphics2D g2 = (Graphics2D) g;
		if (width == 0 && height == 0 && left == 0 && top == 0) {
			g2.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), null);// 绘制图片到面板,控制图片
		} else if ((width != 0 || height != 0) && (left == 0 && top == 0)) {
			g2.drawImage(img, 0, 0, width, height, null);
		} else {
			g2.drawImage(img, left, top, width, height, null);
		}
		
		
		
	}

	// 顺便给你写个测试类吧
	public static void main(String[] args) {
		JFrame frame = new JFrame();
		JPanel panel1 = new JPanel();
		JPanel panel2 = new JPanel();
		panel2.setLayout(new VerticalFlowLayout(VerticalFlowLayout.TOP,5,5,false,false));
		frame.setLayout(new BorderLayout());
		frame.add(panel1, BorderLayout.NORTH);
		frame.add(panel2, BorderLayout.CENTER);
		// 第一个参数图片名字，第二个参数，图片路径，第三四个参数，图片的宽和高
		ImageJButton botton1 = new ImageJButton("这个写你的图片名字，也可以不写，反正有给你写了很多种构造方法",
				"images/8.jpg", 300, 300);
		ImageJButton botton2 = new ImageJButton("/images/reader.png", 50, 50);
		ImageJButton botton3 = new ImageJButton("/images/reader.png", 50, 50);
		panel1.add(botton1);
		panel2.add(botton3);
		panel2.add(botton2);
		frame.setVisible(true);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.pack();
	}

	/*******************************动画处理************************************************/
	/**
	 * This method receives both click events (which start and stop the
	 * animation) and Timer events (which animate the alpha of the button).
	 */
	public void actionPerformed(ActionEvent ae) {

		if (!ae.getSource().equals(this)) {
			// timer event
			// calculate the elapsed fraction
			long currentTime = System.nanoTime() / 1000000;
			long totalTime = currentTime - animationStartTime;
			if (totalTime > animationDuration) {
				animationStartTime = currentTime;
			}
			float fraction = (float) totalTime / animationDuration;
			fraction = Math.min(1.0f, fraction);
			// This calculation will cause alpha to go from 1 to 0 and back
			// to 1
			// as the fraction goes from 0 to 1
			alpha = Math.abs(1 - (2 * fraction));
			// redisplay our button with its new alpha value
			repaint();
		}

		
	}
	
	/**
	 * 功能：改变按钮动画的的状态
	 */
	public void changeAction(){
		if (!timer.isRunning()) {
			animationStartTime = System.nanoTime() / 1000000;
			timer.start();
		} else {
			timer.stop();
			// reset alpha to opaque
			alpha = 1.0f;
		}
		this.updateUI();
	}
	/**
	 * 开始按钮动画
	 */
	public void start(){
		animationStartTime = System.nanoTime() / 1000000;
		timer.start();
		this.updateUI();
	}
	/**
	 * 停止按钮动画
	 */
	public void stop(){
		timer.stop();
		// reset alpha to opaque
		alpha = 1.0f;
	this.updateUI();
	}
	/******************************************************************************************/

	@Override
	public void mouseClicked(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseEntered(MouseEvent e) {
		// TODO Auto-generated method stub
		start();
	}

	@Override
	public void mouseExited(MouseEvent e) {
		// TODO Auto-generated method stub
		stop();
	}

	@Override
	public void mousePressed(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}
}
